<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row>
				<div class="flex justify-between w-full mb8">
					<el-space>
						<el-popover trigger="click" :width="360" placement="bottom-start">
							<el-form :inline="false" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef" label-width="70px">
								<el-row>
									<el-col :span="24" class="mb-4">
										<el-form-item label="所属单位" prop="deptId">
											<el-tree-select
												v-model="state.queryForm.deptId"
												:data="parentData"
												:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
												clearable
												filterable
												multiple
												check-strictly
												tag-type="success"
												:render-after-expand="false"
												placeholder="请选择所属单位"
												:teleported="false"
											/>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form>

							<template #reference>
								<el-button link type="primary"
									>高级搜索<el-icon><ArrowDown /></el-icon>
								</el-button>
							</template>
						</el-popover>
						<el-input placeholder="请输入建筑物地址" v-model="state.queryForm.detailAddress" />
						<el-button type="primary" @click="getDataList(true)">搜索</el-button>
						<el-button icon="refresh" @click="resetQuery()"></el-button>
					</el-space>
					<div>
						<el-button type="success" class="mr-2" @click="formDialogRef.openDialog()" v-auth="'platform_basicPlaceBuilding_add'"> 新增</el-button>
						<!-- 更多操作 -->
						<el-popover :width="168">
							<template #reference>
								<el-button type="primary"
									>更多操作 <el-icon class="ArrowDown"><ArrowDown /></el-icon></el-button
							></template>
							<el-row>
								<el-col :span="24">
									<el-button
										class="ml-3"
										text
										icon="edit"
										:disabled="multiple || selectObjs.length !== 1"
										type="primary"
										@click="formDialogRef.openDialog(selectObjs[0], true)"
										>修改建筑物</el-button
									>
									<el-button
										text
										type="danger"
										:disabled="multiple"
										icon="Delete"
										v-auth="'platform_basicPlaceBuilding_del'"
										@click="handleDelete(selectObjs)"
									>
										删除建筑物
									</el-button>
								</el-col>
							</el-row>
						</el-popover>
					</div>
				</div>
			</el-row>
			<el-table
				:data="state.dataList"
				v-loading="state.loading"
				border
				:cell-style="tableStyle.cellStyle"
				:header-cell-style="tableStyle.headerCellStyle"
				@selection-change="selectionChangHandle"
				@sort-change="sortChangeHandle"
			>
				<el-table-column type="selection" width="40" align="center" />
				<el-table-column type="index" label="序号" width="60" />
				<el-table-column prop="buildingName" label="建筑物名称" show-overflow-tooltip min-width="160" />
				<el-table-column prop="boundFloorCount" label="建筑物楼层数" show-overflow-tooltip min-width="120">
					<template #default="{ row }">
						<el-button link size="small" type="primary" @click="handleFloor(row)">{{ row.boundFloorCount }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="boundInstallCount" label="安装设备数" show-overflow-tooltip min-width="120">
					<template #default="{ row }">
						<el-button link size="small" type="primary" @click="handleInstall(row)">{{ row.boundInstallCount }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="detailAddress" label="建筑物地址" show-overflow-tooltip min-width="240" />
				<el-table-column prop="deptName" label="所属单位" show-overflow-tooltip>
					<template #default="{ row }">
						<div class="text-left">
							<el-popover placement="left" title="所属单位层级关系" :width="200" trigger="click">
								<div v-for="(item, index) in level" :key="item.id">【{{ index + 1 }}】{{ item.name }}</div>
								<template #reference>
									<el-button type="primary" @click="getListAncestorById(row.deptId)" icon="view" size="small" link></el-button>
								</template>
							</el-popover>

							{{ row.deptName }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" show-overflow-tooltip width="180" />
				<el-table-column prop="remarks" label="备注" show-overflow-tooltip />
			</el-table>
			<pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
	</div>
</template>

<script setup lang="ts" name="systemBasicPlaceBuilding">
import { onMounted } from 'vue';
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/installation/basicPlaceBuilding';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { deptTree } from '/@/api/admin/dept';
import { useRouter } from 'vue-router';
import { getListAncestor } from '/@/api/admin/dept';

const router = useRouter();
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典

// 定义变量内容
const formDialogRef = ref();
const parentData = ref([]);
type levelItem = {
	id: string;
	name: string;
};
const level = ref<levelItem[]>([]);
// 搜索变量
const queryRef = ref();
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: fetchList,
	createdIsNeed: false,
	descs: ['create_time'],
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, sortChangeHandle, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	// 清空搜索条件
	queryRef.value?.resetFields();
	// 清空多选
	selectObjs.value = [];
	state.queryForm.detailAddress = '';
	state.queryForm.buildingId = null;
	getDataList();
};

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
	selectObjs.value = objs.map(({ id }) => id);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm('此操作将永久删除');
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
getDeptData();
const handleFloor = (row: { id: string }) => {
	router.push({ path: '/installation/basicPlaceFloor/index', state: { params: { buildingId: row.id } } });
};
const handleInstall = (row: { id: string }) => {
	router.push({ path: '/installation/basicInstallLocation/index', state: { params: { buildingId: row.id } } });
};

const getListAncestorById = (id: string) => {
	level.value = [];
	getListAncestor(id).then((res) => {
		level.value = res.data;
	});
};
onMounted(() => {
	const params = history?.state?.params;
	params?.buildingId && (state.queryForm.buildingId = params?.buildingId);
	getDataList();
	history.state.params = undefined;
});
</script>
